package com.softeng.network.chess;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Vector;

public class ServerHandler implements Runnable
{
	private Socket socket;
	private Server server;
	private String clientID = null;
	
	public ServerHandler( Socket s, Server serv )
	{
		socket = s;
		server = serv;
	}
	
	@Override
	public void run()
	{
		while(true)
		{
			try
			{
				
				Vector<String> removeActions = new Vector<String>();
				
				if( server.getActions().size() > 0 )
				{
					for( int i = 0; i < server.getActions().size(); i++ )
					{
						if( clientID != null)
						{
							NetworkCommand cmd = new NetworkCommand();
							cmd.parse( server.getActions().elementAt( i ) );
							
							if( !cmd.getID().equals( clientID) )
							{
								ObjectOutputStream oos = new ObjectOutputStream( socket.getOutputStream() );
								oos.writeObject( server.getActions().elementAt( i ) );
								removeActions.add( server.getActions().elementAt( i ) );
							}
						}
					}
				}
				
				for( int x = 0; x < removeActions.size(); x++ )
				{
					server.removeAction( removeActions.elementAt( x ) );
				}
				
				if( socket.getInputStream().available() > 0 )
				{
					ObjectInputStream ois = new ObjectInputStream( socket.getInputStream() );
					String action = (String)ois.readObject();
					if( action != null || !action.equals( "" ) )
					{
						server.pushAction( action );
						if( clientID == null)
						{
							NetworkCommand cmd = new NetworkCommand();
							cmd.parse(action);
							clientID = cmd.getID();
						}
					}
				}
			}
			catch( Exception e)
			{
				e.printStackTrace();
			}
		}
	}
}
